//index.js
const addressUrl = 'https://restapi.amap.com/v3/geocode/regeo'
const app = getApp()
var api = require("../../utils/mr_xu/api_url.js").api
var common = require("../../utils/mr_xu/common.js")

Page({
    data: {
        businessConfig: {
            1: "送车",
            2: "找车",
            3: "找车且送到指定地点"
        },
        statusConfig: common.statusConfig,
        tabbar: {},
        menu: [
            // 	{
            //     icon: '/image/db-index-wzcx.png',
            //     title: '违章查询',
            //     url: "/pages/agency/demand/demand-list",
            //     open_type: 'navigate'
            //   },
            {
                icon: '/image/db-index-xzzc.png',
                title: '协助找车',
                url: "/pages/agency/quest/order_list",
                open_type: 'navigate'
            },
            {
                icon: '/image/lp2.png',
                title: '临牌办理',
                url: "/pages/linpai/help",
                open_type: 'navigate'
            },
            {
                icon: '/image/db-index-fx.png',
                title: '分销',
                url: "/pages/common/distribution",
                open_type: 'navigate'
            },
            {
                icon: '/image/db-index-grzx.png',
                title: '个人中心',
                url: "/pages/agency/personal/personal",
                open_type: 'navigate'
            },
        ],
        findCarItems: []
    },
    onLoad: function() {
        app.hidetabbar()
        // app.editTabbar()
        let user = wx.getStorageSync('user')
        this.setData({
            user
        })
        this.getFindCarItems()
        this.getLocation().then(this.loadAddress)
    },
    onShow() {
        this.loadData()
    },
    loadData() {
        let {
            page = 1, rows = 3, agencyList = []
        } = this.data
        wx.showLoading({
            title: '加载中...',
        })
        app.http.post('rest/ticket/queryAgencyList.do', {
            data: {
                page,
                rows,
                orderString: 'updateTime.desc'
            }
        }).then(res => {
            console.log(res, 'xxxxxx')
            agencyList = res.obj.rows
            this.setData({
                agencyList
            })
            wx.hideLoading()
            wx.stopPullDownRefresh()
        })
    },

    /**
     * 获取经纬度
     */
    getLocation() {
        return new Promise((resolve, reject) => {
            app.toPromise(wx.getStorage, {
                key: "location"
            }).then(res => {
                //经纬度已存在
                return Promise.resolve({
                    longitude: res.data.lng,
                    latitude: res.data.lat,
                })
            }).catch(err => {
                return app.toPromise(wx.getLocation, {
                    type: 'gcj02'
                })
            }).then(res => {
                const location = {
                    lng: res.longitude,
                    lat: res.latitude,
                }
                wx.setStorage({
                    key: 'location',
                    data: location,
                })
                this.setData({
                    location
                })
                resolve()
            }).catch(err => {
                this.setData({ //没有授权
                    addressStatus: 1
                })
                reject()
            })
        })
    },
    /**
     * 点击按钮打开设置授权
     */
    handGetLocation() {
        return new Promise((resolve, reject) => {
            app.toPromise(wx.getSetting).then(res => {
                if (res.authSetting['scope.userLocation']) { //已经授权
                    this.setData({
                        addressStatus: 2
                    })
                    resolve(this.getLocation())
                } else { //没有授权
                    this.setData({
                        addressStatus: 1
                    })
                }
            }).catch(err => {
                this.setData({
                    addressStatus: 1
                })
                reject()
            })
        })

    },

    /**
     * 获取地址
     */
    loadAddress() {
        return app.toPromise(wx.request, {
            url: addressUrl,
            data: {
                key: app.globalData.key,
                location: [this.data.location.lng, this.data.location.lat].join(","),
                poitype: '商务住宅',
                extensions: 'all'
            }
        }).then(res => {
            let data = res.data.regeocode
            try {
                this.setData({
                    address: data.formatted_address,
                    city: data.addressComponent.city,
                    // dtCode: data.addressComponent.adcode,
                    // ctCode: data.addressComponent.adcode.slice(0, 4) + '00',
                    pcCode: data.addressComponent.adcode.slice(0, 3) + '000'
                })
            } catch (err) {
                this.setData({
                    address: data.addressComponent.province + data.addressComponent.city + data.addressComponent.district + data.addressComponent.street,
                    city: data.addressComponent.city
                })
            }
            wx.setStorage({
                key: 'address',
                data: this.data.address,
            })
            wx.setStorage({
                key: 'pcCode',
                data: this.data.pcCode,
            })
        })
    },
    //打开定位地址
    openLocation() {
        wx.openLocation({
            latitude: this.data.location.lat,
            longitude: this.data.location.lng,
            address: this.data.address
        })
    },
    openSetting() {
        this.handGetLocation().then(this.loadAddress)
    },
    // //搜索
    // search(evt) {
    //     let value = evt.detail.value
    //     wx.navigateTo({
    //         url: './demand/demand-list?keywords=' + value,
    //     })
    // },
    toDetail(evt) {
        let {
            cid,
            id,
            status
        } = evt.currentTarget.dataset
        if (status == 2) {
            return
        }
        let url = ''
        if (status == 1) {
            url = '/pages/agency/demand/offer-success'
        }
        if (status == 3 || status == 5 || status == 6 || status == 4) {
            url = '/pages/agency/demand/bidding-success'
        }
        // if (status == 4) {
        //     url = '/pages/agency/demand/bidding-success'
        // }
        wx.navigateTo({
            url: url + '?id=' + id + '&cid=' + cid,
        })
    },
    onPullDownRefresh() {
        this.loadData()
    },
    onShareAppMessage() {

    },
    getFindCarItems() {
        let that = this
        app.http.post(api.agency_find_car_index, {
                data: {
                    page: 1,
                    rows: 3,
                    orderString: 'createTime.desc'
                }
            })
            .then(res => {
                let rows = res.obj.rows
                for (let i in rows) {
                    let item = rows[i]
                    let showLimit = item.limitTime && common.strtotime(item.limitTime) > (new Date()).getTime() / 1000 ? true : false
                    if (item.limitPrice && showLimit) {
                        rows[i].price = parseInt(item.price) + parseInt(item.limitPrice)
                    }
                    rows[i].showLimit = showLimit
                }
                that.setData({
                    findCarItems: rows
                })
            })
    },
    toFindCarList() {
        wx.navigateTo({
            url: '/pages/agency/quest/order_list?fromway=personal',
        })
    },
    toFindCarDetail(e) {
        console.log(e)
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: '/pages/agency/quest/order_info?fromway=personal&id=' + id,
        })
    }
})